﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using i_core;
using common;
using Autofac;

namespace client35 {
	public class SocketManage {
		private Socket _Client = null;
		public bool IsExit = true;
		private string _serverIP;
		private int _serverPort;

		private readonly i_log log;

		public SocketManage() {
			log = global_vars.scope.ResolveKeyed<i_log>(log_type.serilog,
				new NamedParameter("user", "socket"),
				new NamedParameter("islog", true));
		}
		/// <summary>
		/// 新建Socket连接
		/// </summary>
		/// <returns>返回连接是否成功</returns>
		public bool CreateNewConn() {

			bool result = false;
			try {
				_Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
				IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(this._serverIP), this._serverPort);
				try {
					_Client.Connect(ipep);
					this.IsExit = false;
					new Thread(new ThreadStart(ReceiveData)).Start();
					result = true;
				} catch (Exception ex) {
					log.Error("连接目标服务器失败", ex);
				}
			} catch (Exception ex) {
				log.Error("创建Socket连接失败", ex);
			}
			return result;
		}

		/// <summary>
		/// 接收服务器发送的消息
		/// </summary>
		private void ReceiveData() {
			try {
				int errorCount = 0;
				while (!this.IsExit) {
					byte[] databyte = new byte[65535];
					int recv = _Client.Receive(databyte);
					if (recv == 0) {
						errorCount++;
						if (errorCount > 3) {
							log.Error("服务器端无限制发送连接错误空字符串");
							this.IsExit = true;
							return;
						}
						continue;
					}
					string dataStr = Encoding.UTF8.GetString(databyte, 0, recv);
					if (dataStr == "Error") {
						log.Error("接收到错误停止命令Error");
						break;
					}
					ReceiveDataEvent?.Invoke(dataStr, _Client);
				}
			} catch (Exception ex) {
				log.Error("SocketManage.cs中执行ReceiveData()接受数据时报错 " + ex.Message, "Socket_Error");
				IsExit = true;
			}
		}

		/// <summary>
		/// 关闭socket连接
		/// </summary>
		public void Close() {
			try {
				if (!IsExit) {
					this.AsyncSendToServer("STOP");
					IsExit = true;
					_Client.Close();

				}

			} catch (Exception ex) {
				log.Error("SocketManage.cs中执行Close()时报错 " + ex.Message);
			}
		}

		/// <summary>
		/// 异步想服务器发送信息
		/// </summary>
		/// <param name="message"></param>
		public void AsyncSendToServer(string message) {
			try {
				log.Info("向远程电话服务器发送信息: " + message);
				SendToServerDelegate sd = new SendToServerDelegate(SendToServer);
				IAsyncResult iresult = sd.BeginInvoke(message, null, null);
				while (iresult.IsCompleted == false) {
					if (IsExit) break;
					Thread.Sleep(250);
				}
				sd.EndInvoke(iresult);
			} catch (Exception ex) {
				log.Error("向远程电话服务器发送信息失败：" + ex.Message);
			}
		}

		/// <summary>
		/// 向服务器端发送信息
		/// </summary>
		/// <param name="message"></param>
		public void SendToServer(string message) {
			try {
				Byte[] sendData = Encoding.UTF8.GetBytes(message);
				if (!IsExit) {
					_Client.Send(sendData);
				}
			} catch (Exception ex) {
				log.Error("向远程电话服务器发送信息失败", ex);
			}
		}

		private delegate void SendToServerDelegate(string message);
		public delegate void SocketReceiveData(string msg, Socket _Socket);
		public event SocketReceiveData ReceiveDataEvent;

		/// <summary>
		/// 监听端口号
		/// </summary>
		public int ServerPort {
			get { return _serverPort; }
			set { _serverPort = value; }
		}

		/// <summary>
		/// 服务器IP
		/// </summary>
		public string ServerIP {
			get { return _serverIP; }
			set { _serverIP = value; }
		}



		public Socket Client {
			get { return _Client; }
			set { _Client = value; }
		}


	}
}
